package com.example.leetdemo.process;

public class Solution1669 {
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        ListNode p = list1, q = list2, end = p;
        boolean flag = true;
        while(true) {
            if(p.next != null && p.next.val == a && flag) {
                end = p.next;
                flag = false;
                p.next = q;
                while(end != null) {
                    if(end.val == b) {
                        end = end.next;
                        break;
                    }
                    end = end.next;
                }
            }
            if(p.next == null) {
                p.next = end;
                break;
            }
            p = p.next;
        }
        return list1;
    }
}
